package com.zmc.third.application.factory.service.alipay;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.zmc.common.domain.vo.order.OrderPayInfo;
import com.zmc.common.utils.R;
import com.zmc.third.infrastructure.bean.resp.PayChannelResp;
import com.zmc.third.infrastructure.constant.StateCodeConstant;
import com.zmc.third.infrastructure.entity.PaymentInfoEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author：zmc
 * @Date：2024/11/8 21:19
 * 订单码支付
 */

@Component
public class OrderPayPayServiceImpl implements AlipayService {

    public static Logger log = LoggerFactory.getLogger(OrderPayPayServiceImpl.class);

    @Override
    public R requestPayChannel(AlipayClient alipayClient, PaymentInfoEntity paymentInfo, String notifyUrl, String returnUrl) {
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(paymentInfo.getTradeSn());
        model.setSubject(paymentInfo.getSubject());
        model.setTotalAmount(paymentInfo.getTotalAmount().toString());
        model.setProductCode("QR_CODE_OFFLINE");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        try {
            AlipayTradePrecreateResponse res = alipayClient.execute(request);
            log.info("alipay请求获取支付码结果，response:{}", JSON.toJSONString(res));
            if (StateCodeConstant.ALIPAY_REQUEST_PAY_CODE_SUCCESS.equals(res.getCode())) {
                return R.ok(new PayChannelResp(res.getQrCode(), false));
            }
        } catch (AlipayApiException e) {
            log.error("alipay请求获取支付码异常", e);
        }
        return R.error("获取支付码失败，请稍后重试");
    }

}
